package net.midnighttd.engine.entity;

import java.util.*;
import java.awt.Point;


/**
 * Author: Adam Scarr
 * Date: 22/04/2009
 * Time: 10:33:34 PM
 *
 * Stores entitys in a way that can be located quickly based upon spatial coordinates.
 */
public class EntityMap {
    private Map<Point, EntityList> entities = new HashMap<Point, EntityList>();

    public synchronized EntityList get(int x, int y) {
        Point key = new Point(x, y);
        EntityList peg = entities.get(key);

        if(peg == null) return new EntityList();

        return new EntityList(peg);
    }

    public synchronized Entity add(Entity e) {
        int x = e.getX();
        int y = e.getY();
        Point key = new Point(x, y);

        EntityList peg = entities.get(key);
        if(peg == null) {
            peg = new EntityList();
            entities.put(key, peg);
        }
        peg.add(e);

        return e;
    }

    public synchronized Entity remove(Entity e, int x, int y) {
        Point key = new Point(x, y);
        EntityList peg = entities.get(key);


        if(peg == null) {
            if(!(x == 0 && y == 0)) {
                System.out.println("Warning couldn't remove old ent " + e.getName() + " from " + x + "," + y);
            }
            return e;
        }

        peg.remove(e);

        return e;
    }

    public synchronized void move(Entity e, int fromX, int fromY) {
        remove(e, fromX, fromY);
        add(e);
    }

    public synchronized EntityList getAll() {
        EntityList list = new EntityList();

        for(EntityList l: entities.values()) {
            list.addAll(l);
        }

        return list;
    }

    public synchronized void clear() {
        entities.clear();
    }
}
